module Table
  ################################# 
  # Class to represent a 'workbook'
  # accessor's:
  # @tables array of Table::RTable 's
  # @bname book name
  # @fpath file path to write dir
  class RBook
    include Table
    attr_accessor :bname,:fpath,:tables
    def initialize
      super
      @tables = []
      @bname = "UntitledBook"
      @fpath = ENV['HOME']
    end
  
    # append table x to self
    def add x
      x.book=self
      @tables << x
    end

    def push x
      x.book=self
      @tables << x
    end

    # dump me (not like my ex did however :( )
    # save the RBook
    def write_book
       file = File.join(@fpath,@bname+".rts")
       File.open(file,'w'){|f| YAML.dump(self,f)}
       file
    end

    #################################
    # this generates static html
    # files containing formatting
    # if borders==true draw table and td borders
    # if old_html is true use old html color and font tags, else use styles
    def static_export borders=true,old_html=nil
      #     iterate over tables
      files = []
      sheets = "Sheets: "
      for i in 0..length-1
        sheets = sheets + "<a href=#{@bname}#{i}.html>#{i}</a> "
      end
      @tables.each_with_index do |tbl,i|
        table=tbl.clone
        table.rows = tbl.clone.rows.clone
        b=""
        if borders
          b = "border=1" # draw table borders and td borders
        end
        html = "<html><body>#{sheets}<br><table #{b}>\n"
        # the out file
        file = File.join(@fpath,@bname+"-sheet.#{i}.html")
        files << file
        hfile = File.open(file,'w')
        hfile.puts html
        hfile.puts "<tr><td>#</td>"
        # column numbers 
        for i in 0..table.length[1]
          hfile.puts "<td>#{i}</td>"
        end
        hfile.puts "</tr>"
        table.rows.each_with_index {|ro,r|
          row = ro.clone
          hfile.puts "<tr><td>#{r}</td>" # row numbers
          # add cells to row if needed (draws a pretty table)
          if row[:cols].length-1 < table.length[1]
              table.rows[r][:cols] = table.rows[r][:cols].clone
            for i in 0..(table.length[1] - row[:cols].length-1)+1
              row[:cols] << "&nbsp;"
            end
          end
          # iterate cells in row
          row[:cols].each_with_index {|col,c|
            # 1m bold 3m italic 4m underline 9m strik
            tags = %w[<b> <i> <u> <del>]
            tend = %w[</b> </i> </u> </del>]
            ansi = abs_format(table,r,c) #ansi seq string
            ansi = "" unless ansi
            # colors
            bg = ansi.scan(/\[4[0-9]m/)[0]
            fg = ansi.scan(/\[3[0-9]m/)[0]
            if fg =~ /([0-9]+)/
              fg = $1
            else
              fg = nil
            end
            if bg =~ /([0-9]+)/
              bg=$1
            else
              bg = nil
            end
            fg = get_color_num fg.to_i if fg
            bg = get_color_num bg.to_i if bg
            bg = "" unless bg;fg="" unless fg
            # underloine bold italic strike
            font=[];fontend=[]
            %w[1m 3m 4m 9m].each_with_index {|a,i|
              if ansi.index("\e[#{a}")
                font << tags[i];fontend << tend[i]
              end
            }
            col=col.clone
            col = "" if col==nil
            # td style and content
            if old_html
              hfile.puts "<td #{b} bgcolor=#{bg.to_s}>#{font}<font face=courier color=#{fg}>#{col.gsub(/\ /,'&nbsp;')}</font>#{fontend}</td>"
            else
              hfile.puts "<td #{b} style=font-family:mono;background:#{bg.to_s};color:#{fg.to_s}>#{font}#{col.gsub(/\ /,'&nbsp;')}#{fontend}</td>"
            end
          }
          hfile.puts "</tr>"
        }
        hfile.puts "<body></table></html>\n"
        hfile.close
      end
      files
    end

    # make a excel book from me
    # writes all tables in book and book 
    # as excel woorkbook,worksheets
    # name is @bname and sheet where sheet is index of table
    def to_excel
      @book = create_book
      @tables.each_with_index do |table,i|
        p make_sheet(@book,@bname+i.to_s,table)
      end
      p @book
    end

    def length
      @tables.length
    end

    # save excel
    # write the excel book to file @bname+'.xls'
    def write_excel
      @book.write File.join(@fpath,@bname+".xls")
      File.join(@fpath,@bname+".xls")
    end
    alias :write_html :static_export
    alias :<< :push
    alias :to_html :static_export
  end
end